// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const {
    deliveryMan,
    orderId,
    cancel
  } = event

  try {
    const _ = db.command
    let res = {}
    if (!cancel) {
      res = await db.collection('orders')
        .where(_.and({
          _id: orderId,
          deliveryMan: _.exists(false),
          status: _.eq('待配送'),
        }, _.or({
          payStatus: _.eq('success'),
        }, {
          payStatus: _.eq('wait'),
          payOffline: _.eq(true),
        })))
        .update({
          data: {
            deliveryMan,
            status: '配送中',
            arrivalTips: arrivalTips()
          }
        })
    } else { // cancel    
      res = await db.collection('orders')
        .where(_.and({
          _id: orderId,
          deliveryMan,
          status: _.eq('配送中'),
        }, _.or({
          payStatus: _.eq('success')
        }, {
          payStatus: _.eq('wait'),
          payOffline: _.eq(true),
        })))
        .update({
          data: {
            deliveryMan: _.remove(),
            status: '待配送',
            arrivalTips: ''
          }
        })
    }
    return res
  } catch (err) {
    console.error(err)
    return err
  }
}

const arrivalTips = () => {
  const curDate = new Date()
  curDate.setHours(curDate.getHours() + 2 + 8) // 2小时送达，UTC与北京时间相差8小时
  const month = prefixZero(curDate.getMonth() + 1),
    day = prefixZero(curDate.getDate()),
    hour = prefixZero(curDate.getHours()),
    minute = prefixZero(curDate.getMinutes())
  return `${month}-${day} ${hour}:${minute}`
}

const prefixZero = (num) => {
  return num < 10 ? '0' + num : num
}